var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerList: [],
    bannerData: {
      indicatorDots: false,
      vertical: false,
      autoplay: false,
      interval: 2000,
      duration: 500,
      indicator_color: '#fff',
      indicator_active_color: 'rgba(255, 83, 60, 1)',
    },
    bannerNum: 1,
    cur: 1,
    goodsData: {},
    type: '',
    height:300,
    state: wx.getStorageSync('state'),
    states: false,
    btnState:false,
    bgcolor: home.getKey('bgcolor'),
  },

  toCart() {
    wx.switchTab({
      url: '../../pages/car/index',
    });
  },

  //加入购物车
  addCar() {
    let that = this;
    let createTime = home.js_date_time(new Date() / 1000);
    let goodsData = this.data.goodsData
    if (goodsData.cartNum >= goodsData.inventory) {
      home.wxMessage('库存不足','error');
      return false;
    }
    wx.request({
      url: url + 'shopcommoditycart/ShopCommodityCart/add',
      data: {
        memberId:home.getKey('userId'),
        storeId:home.getKey('storeId'),
        createBy:'system',
        createTime:createTime,
        updateBy:'',
        updateTime:'',
        sysOrgCode:'',
        qty:1,
        commodityId:goodsData.id,
        commodityName:goodsData.tradeName,
        commoditySpec:goodsData.specification,
        commodityPic:goodsData.productPic,
        price:goodsData.productPrice,
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        let msg = '';
        let icon = '';
        if (res.data.code == 200) {
          msg = '添加成功';
          icon = 'success';
          goodsData.cartNum += 1;
          that.setData({
            goodsData: goodsData,
            btnState1:false,
          });
        } else {
          msg = '添加失败';
          icon = 'none';
        }
        wx.showToast({
          title: msg,
          icon: icon
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //url传递过来，重新分组//王重阳
    let goodsData = JSON.parse(options.info);
    let bannerNum = 0;
    let bannerList = [];
    if (goodsData.productPic) {
      bannerList = goodsData.productPic.split(',');
      bannerNum = bannerList.length;
      for (let i = 0; i < bannerList.length; i++) {
        bannerList[i] = 'https://kyz.fbhkj.com//' + bannerList[i];
      }
      if(goodsData.detailsUrl != null)
      {
        let detailsUrl = goodsData.detailsUrl.split(',');
        for (let i = 0; i < detailsUrl.length; i++) {
          detailsUrl[i] = 'https://kyz.fbhkj.com//' + detailsUrl[i];
        }
        goodsData.detailsUrl = detailsUrl;
      }
      
    }
    goodsData.num = 0;
    this.setData({
      goodsData: goodsData,
      bannerList: bannerList,
      bannerNum: bannerNum,
      states:false,
      state: wx.getStorageSync('state'),
    });
  },

  /**
   * banner切换
   */
  onChange(e) {
    this.setData({
      cur: e.detail.current + 1
    });
  },

  //跳转确认订单页面
  toOrder() {
    let goodsData = this.data.goodsData;
    let goods = {};
    goods.goodsId = goodsData.id;
    goods.commodityPic = goodsData.productPic;
    goods.price = goodsData.productPrice;
    goods.qty = 1;
    goods.commoditySpec = goodsData.specification;
    goods.commodityName = goodsData.tradeName;
    goods.type = 1;
    let data = []; 
    data.push(goods);
    wx.navigateTo({
      url: '../../user/order/info?data=' + JSON.stringify(data),
    });
  },
        //小程序授权
        login() {
          wx.showLoading({
            title: '加载中...',
          })
          this.setData({
            btnState:false,
          });
          let that = this;
          wx.getUserProfile({
            desc: '用于完善会员资料',
            success: function (ress) {
              wx.login({
                success(res) {
                  wx.request({
                    url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/updateUserNickName?storeId=' + app.globalData.storeId + '&code=' + res.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId') + '&nickName' + ress.userInfo.nickName + '&headPortrait=' + ress.userInfo.avatarUrl + '&sex=保密',
                    data: {
                      storeId: app.globalData.storeId,
                      nickName: ress.userInfo.nickName,
                      headPortrait: ress.userInfo.avatarUrl,
                      sex: '保密',
                      xcxOpenId: wx.getStorageSync('openId'),
                      unionId: wx.getStorageSync('unionId')
                    },
                    method: 'POST',
                    header: {
                      "content-type": "application/json", // 默认
                    },
                    success: function (rea) {
                      if (rea.data.code == 200) {
                        wx.hideLoading({
                          success: (res) => {
                            that.setData({
                              btnState: true,
                              states:false,
                              state:2
                            })
                          },
                        })
                        wx.setStorageSync('nickName', ress.userInfo.nickName);
                        wx.setStorageSync('avatar', ress.userInfo.avatarUrl);
                        that.setData({
                          state: 2
                        });
                        wx.setStorageSync('state', 2);
                      }
                    }
                  })
                }
              })
            },
            fail: function (res) {
              that.setData({
                btnState: true,
              })
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 1500,
              })
            }
          })
        },
        register() {
          wx.showLoading({
              title: '加载中...',
          });
          let that = this;
          wx.login({
              success(res) {
                  wx.request({
                      url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
                      data: {
                          storeId: app.globalData.storeId,
                          code: res.code
                      },
                      method: 'POST',
                      header: {
                          "content-type": "application/json", // 默认
                      },
                      success: function (rea) {
                          if (rea.data.code == 200) {
                              let states = false;
                              if (!rea.data.result.hasPhone) {
                                  that.setData({
                                      state: 1
                                  });
                                  //home.setKey('state', 1);
                                 // wx.setStorageSync('state', 1);
                              } else if (!rea.data.result.hasNickName) {
                                  states = true;
                                  that.setData({
                                      state: 0
                                  });
                                  //home.setKey('state', 0);
                                  //wx.setStorageSync('state', 0);
                              }
                              home.setKey('subscribeTencent', rea.data.result.subscribeTencent);
                              home.setKey('hasNickName', rea.data.result.hasNickName);
                              home.setKey('hasPhone', rea.data.result.hasPhone);
                              home.setKey('userId', rea.data.result.member.id);
                              home.setKey('phone', rea.data.result.member.phone);
                              home.setKey('avatar', rea.data.result.member.avatarUrl);
                              home.setKey('status', rea.data.result.member.status);
                              home.setKey('discount', rea.data.result.member.discount);
                              home.setKey('nickName', rea.data.result.member.nickName);
                              home.setKey('openId', rea.data.result.member.xcxOpenId);
                              home.setKey('unionId', rea.data.result.member.unionId);
                              let states1 = false;
                              if (rea.data.result.hasPhone && rea.data.result.hasNickName) {
                                  states1 = !rea.data.result.subscribeTencent;
                                  that.setData({
                                      state: 2
                                  });
                                  home.setKey('state', 2);
                                  wx.setStorageSync('state', 2);
                                  that.getUserInfos();
                              }
                              that.setData({
                                  states: states,
                                  states1: states1,
                              })
                              wx.hideLoading({
                                  success: (res) => {
  
                                  },
                              })
                          } else {
                              home.wxMessage(rea.data.message, 'none');
                          }
                      }
                  })
              }
          })
      },
        getPhoneNumber(e) {
          console.log(e.detail);
          wx.showLoading({
            title: '加载中...',
          });
          this.setData({
            btnState1:false,
          })
          if (e.detail.code == undefined) {
            wx.showToast({
              title: '请授权获取手机号',
              icon: 'none',
              duration: 1500,
            })
            wx.setStorageSync('state', 1);
            this.setData({
              btnState1:true,
            })
            return false;
          }
          let that = this;
          wx.request({
            url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/getPhone?storeId=' + app.globalData.storeId + '&code=' + e.detail.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId'),
            data: {
              storeId: app.globalData.storeId,
              code: e.detail.code,
              xcxOpenId:wx.getStorageSync('openId'),
              unionId:wx.getStorageSync('unionId')
            },
            method: 'POST',
            header: {
              "content-type": "application/json", // 默认
            },
            success: function (res) {
              if (res.data.code == 200) {
                wx.hideLoading({
                  success: (res) => {
                    that.setData({
                      btnState1: true,
                    });
                  },
                })
                wx.setStorageSync('phone', res.data.result.phone);
                wx.setStorageSync('userId', res.data.result.id);
                let state = 2;
                
                if (!wx.getStorageSync('hasNickName')) {
                  state = 0;
                }
                
                that.setData({
                  state: state
                });
                wx.setStorageSync('state', state);
              } else {
                wx.showToast({
                  title: '获取失败',
                  icon: 'none',
                  duration: 1500,
                })
              }
            }
          })
        },
        onClose1() {
          this.setData({
              states: false,
          })
      },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height:res.windowWidth
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})